import React, { useState, Fragment, useRef, useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Button from '@material-ui/core/Button'
import Paper from '@material-ui/core/Paper'
import Divider from '@material-ui/core/Divider'
import ProxyItem from './components/ProxyConfig/ProxyItem.jsx'
import { MSG_TYPES } from '../utils/MESSAGE_TYPES'

const useStyles = makeStyles((theme) => ({
    root: {
        padding: '10px',
        width: '600px',
        minHeight: '200px',
        maxHeight: '400px',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between'
    },
    header: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    btnGroup: {
        display: 'flex',
        justifyContent: 'flex-end'
    },
    list: {
        height: '100%',
        overflowY: 'scroll'
    }
}));

function getStorage() {
    try {
        return JSON.parse(localStorage.getItem('PROXY_ROUTES')) || []
    } catch (e) {
        return []
    }
}
function setStorage(obj) {
    try {
        localStorage.setItem('PROXY_ROUTES', JSON.stringify(obj))
        // 发送
        sendMessageToContentScript({
            event: MSG_TYPES.matchingUpdate,
            data: obj
        });

    } catch (e) {
        console.log(e)
    }
}

function sendMessageToContentScript(message, callback) {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
            if (callback) callback(response);
        });
    });
}

export default function () {
    const classes = useStyles()
    const [proxyRoutes, setProxyRoutes] = useState(getStorage())

    function reset() {
        setProxyRoutes(getStorage())
    }

    function addNew() {
        setProxyRoutes(proxyRoutes.concat(new ProxyDataModel()))
    }

    function onDel(index) {
        proxyRoutes.splice(index, 1)
        setProxyRoutes([...proxyRoutes])
    }

    function save() {
        setStorage(proxyRoutes)
    }

    function onItemChange(index, changeValues) {
        proxyRoutes[index] = {
            ...proxyRoutes[index],
            ...changeValues
        }
        setProxyRoutes([...proxyRoutes])
    }

    return <Paper elevation={3} className={classes.root}>
        {/* 头部 */}
        <div>
            <div className={classes.header}>
                <div>代理路径</div>
                <Button color="primary" size='small' onClick={addNew}>新建</Button>
            </div>
            <Divider />
        </div>
        {/* 配置 */}
        <div className={classes.list}>
            {
                proxyRoutes.map((item, index) => <Fragment>
                    <ProxyItem
                        value={item}
                        onChange={(changeValues) => {
                            onItemChange(index, changeValues)
                        }}
                        onDel={() => {
                            onDel(index)
                        }}
                    />
                    {
                        index === proxyRoutes.length - 1
                            ? null
                            : <Divider />
                    }
                </Fragment>)
            }
        </div>
        {/* 按钮组 */}
        <div className={classes.btnGroup}>
            <Button variant="contained" size='small' color="secondary" onClick={reset} style={{ marginRight: '10px' }}>放弃修改</Button>
            <Button variant="contained" size='small' color="primary" onClick={save}>应用修改</Button>
        </div>
    </Paper>
}

class ProxyDataModel {
    matching = ''
    enable = false
}
